package cn.matrix42.potoo.format.markdown.element.chart.table;

import java.util.ArrayList;
import java.util.List;

import cn.matrix42.potoo.format.markdown.element.MarkdownElement;
import cn.matrix42.potoo.lang.Preconditions;

public class Table extends MarkdownElement {

    private final int column;
    private final List<TableRow> tableContent = new ArrayList<>();

    public Table(int column) {
        Preconditions.checkArgument(column > 0);
        this.column = column;
    }

    public TableHeader addHeader() {
        if (tableContent.size() > 0) {
            throw new IllegalStateException("Header must be add first.");
        }
        TableHeader header = new TableHeader(column);
        header.setup(context);
        tableContent.add(header);
        return header;
    }

    public TableRow addRow() {
        if (tableContent.size() == 0) {
            throw new IllegalStateException("Row can't be add first.");
        }
        TableRow tableRow = new TableRow(column);
        tableRow.setup(context);
        tableContent.add(tableRow);
        return tableRow;
    }

    public void setContent(int row, int column, String content) {
        Preconditions.checkArgument(column < this.column);
        tableContent.get(row).set(column, content);
    }

    public int getRow() {
        return tableContent.size();
    }

    public int getColumn() {
        return column;
    }

    @Override
    public List<String> toMarkdownStringList() {
        return toMarkdownStringList(context.getConfig().getEof(), tableContent);
    }

    public static List<String> toMarkdownStringList(String eofString, List<TableRow> tableContent) {
        List<String> list = new ArrayList<>();
        for (TableRow tableRow : tableContent) {
            list.add(tableRow.toMarkdownString());
        }
        list.add(eofString);
        return list;
    }

}
